package com.fl.iocaop.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

import com.fl.iocaop.aop.TestAop;
/**
 * 创建jdk代理类
 */
public class JDKProxy {
    public static void main(String[] args) {
        Class[] interfaces = {UserDaoAop.class};
        UserDaoImpl userDao = new UserDaoImpl();
        UserDaoAop Aop = (UserDaoAop)Proxy.newProxyInstance(Proxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        int add = userDao.add(12, 11);
        System.out.println("add = " + add);

    }
    static class UserDaoProxy implements InvocationHandler{
        //创建的是谁的代理对象，就把对象传过来
        //有参构造传递
        private Object object;
        public UserDaoProxy(Object obj){
            this.object = obj;
        }
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            //方法执行之前
            System.out.println("方法执行之前->"+method.getName()+"--传递参数->"+ Arrays.toString(args));
            //被增强的方法执行
            Object invoke = method.invoke(object, args);
            //方法执行之后
            System.out.println("方法执行之后->"+object);
            return invoke;
        }
    }
}
